<template>
  <page-meta :root-font-size="fontSizeStore.currentFontSizeRpx"></page-meta>
  <HeadNav :title="pageTitle" />
  <view class="online-supermarket">
    <view class="supermarket-layout">

      <!-- 左侧菜单 -->
      <scroll-view class="category-menu" scroll-y :scroll-into-view="leftScrollInto" scroll-with-animation>
        <view v-for="(category, index) in categories" :key="index" :id="`left-item-${index}`"
          class="category-menu__item" :class="{ 'category-menu__item--active': activeIndex === index }"
          @click="handleCategoryMenuClick(index)">
          <text class="cat_name">{{ category.name }}</text>
        </view>
      </scroll-view>

      <!-- 右侧内容 -->
      <view class="content-panel" @touchmove.stop>
        <view class="sort_view">
          <wd-sort-button :line="true" custom-class="sort_size" title="价格" v-model="priceSortValue"
            @change="priceSorthandleChange" />
          <wd-search placeholder-left hide-cancel />
        </view>


        <!-- 商品列表（修复滚动事件触发问题） -->
        <scroll-view ref="rightScrollRef" id="rightScrollView" class="content-goods__scroll" scroll-y="true"
          :scroll-into-view="targetId" scroll-with-animation @scroll="handleRightScroll">
          <view class="content-goods__container">
            <!-- 关键：确保分类标题ID与计算位置的选择器完全匹配 -->
            <view class="category-card" v-for="(category, index) in filteredCategories" :key="index"
              :id="`right-category-${index}`">
              <view class="category-card__title text12" :id="`category-title-${index}`">
                {{ category.name }}
                <span class="category-count text12">({{ category.filteredFoods.length }})</span>
              </view>

              <view v-if="category.filteredFoods.length === 0" class="no-results">
                没有找到符合条件的商品
              </view>

              <view v-for="food in category.filteredFoods" :key="food.id" class="goods-item">
                <view class="goods-item__img">
                  <image
                    :src="food.imageUrl || 'https://p0.meituan.net/coverpic/4e9b9e5a742ddfc29f9efb8c7033dbe21323862.jpg%40538w_717h_1e_1c_1l%7Cwatermark%3D0'"
                    :alt="food.name">
                  </image>
                </view>
                <view class="goods-item__info">
                  <view>
                    <text class="goods-item__name text11">{{ food.name }}</text>
                    <view v-if="food.isRecommend" class="recommend-badge">推荐</view>
                  </view>
                  <view class="goods-item__sales text11">销量: {{ food.sales }}份</view>
                  <view>
                    <text class="goods-item__price text11">￥{{ food.price }}</text>
                  </view>
                </view>

                <view class="goods-item__count">
                  <view v-if="food.count > 0" class="count-btn count-btn--minus text11"
                    @click="handleGoodsCountChange(food, -1)">-</view>
                  <text v-if="food.count > 0" class="count-btn__num text11">{{ food.count }}</text>
                  <view class="count-btn count-btn--plus text11" @click="handleGoodsCountChange(food, 1)">+
                  </view>
                </view>
              </view>
            </view>
            <view class="content-goods__spacer"></view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 底部导航 -->
    <view class="bottom-nav" v-if="!showBottomModel && !isFilterPopupOpen">
      <view class="bottom-nav__cart" @click="handleShowPaymentPopup">
        <view class="cart__wrap">
          <wd-icon name="cart" size="22px"></wd-icon>
          <view v-if="cartCount > 0" class="cart__badge" :class="{ 'cart__badge--dot': cartCount === 0 }">
            {{ cartCount > 99 ? '99+' : cartCount }}
          </view>
        </view>
        <view class="cart__text">购物车</view>
      </view>
      <view class="bottom-nav__price">
        <view class="price__content">
          <text class="price__symbol">¥</text>
          <text class="price__amount">{{ cartTotalAmount }}</text>
        </view>
        <view class="price__desc">配送费</view>
      </view>
      <view class="bottom-nav__reserve">
        <wd-button @click="actionCart" type="error" size="medium" class="reserve__btn" :disabled="cartCount === 0">
          立即预约
        </wd-button>
      </view>
    </view>


  </view>

  <view class="payment-popup">
    <wd-action-sheet title="我的购物车" v-model="showBottomModel" @close="handleHidePaymentPopup">
      <!-- 修复scroll-view拼写错误 + 限制滚动高度 -->
      <scroll-view class="cart-scroll" scroll-y style="max-height: 70vh;">
        <view class="cart_view">
          <!-- 购物车为空状态 -->
          <view v-if="cartGoods.length === 0" class="empty-cart">
            <wd-icon name="cart" size="60px" color="#ccc"></wd-icon>
            <text class="empty-text">购物车是空的哦~</text>
          </view>

          <!-- 购物车列表 -->
          <view v-else class="cart-list">
            <!-- 按分类显示购物车商品 -->
            <view v-for="(category, catIndex) in cartCategories" :key="catIndex" class="cart-category">
              <!-- 分类标题栏：flex布局，勾选框居左，删除按钮居右 -->
              <view class="category-header">
                <!-- 左侧：分类勾选框 + 分类名 -->
                <view class="category-selector">
                  <wd-checkbox v-model="category.checked" @change="handleCategoryCheck(catIndex)" shape="circle"
                    class="checkbox-left"></wd-checkbox>
                  <text class="category-name">{{ category.name }}</text>
                </view>
                <!-- 右侧：删除分类按钮 -->
                <wd-button type="text" text-color="#ff4d4f" size="small" @click="handleDeleteCategory(catIndex)"
                  class="delete-category" :disabled="!category.goods.some(item => item.checked)">
                  删除分类
                </wd-button>
              </view>

              <!-- 分类下的商品列表 -->
              <view class="category-goods">
                <!-- 商品项：flex布局，勾选框居左，信息+数量控件居右 -->
                <view v-for="(item, itemIndex) in category.goods" :key="itemIndex" class="cart-item">
                  <!-- 左侧：商品勾选框（单独一列，居左） -->
                  <view class="item-checkbox-col">
                    <wd-checkbox v-model="item.checked" @change="handleItemCheck(catIndex, itemIndex)" shape="circle"
                      class="checkbox-left"></wd-checkbox>
                  </view>

                  <!-- 右侧：商品信息 + 数量控件（占剩余宽度） -->
                  <view class="item-content">
                    <view class="item-info">
                      <image
                        :src="item.imageUrl || 'https://p0.meituan.net/coverpic/4e9b9e5a742ddfc29f9efb8c7033dbe21323862.jpg'"
                        class="item-img"></image>
                      <view class="item-details">
                        <text class="item-name">{{ item.name }}</text>
                        <text class="item-price">￥{{ item.price }}</text>
                      </view>
                    </view>

                    <!-- 第三列：数量控件 -->
                    <view class="item-quantity">
                      <view class="count-btn count-btn--minus text11" @click="handleCartCountChange(item, -1)"
                        :class="{ 'count-btn--disabled': item.count <= 1 }">
                        -
                      </view>
                      <text class="count-btn__num text11">{{ item.count }}</text>
                      <view class="count-btn count-btn--plus text11" @click="handleCartCountChange(item, 1)">
                        +
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>

            <!-- 批量删除栏：flex布局，全选居左，批量删除居右 -->
            <view class="batch-operation">
              <!-- 左侧：全选框 + 全选文本 -->
              <view class="select-all-wrap">
                <wd-checkbox v-model="selectAll" @change="handleSelectAll" shape="circle"
                  class="checkbox-left"></wd-checkbox>
                <text class="select-all-text">全选</text>
              </view>
              <!-- 右侧：批量删除按钮（margin-left:auto 实现居右） -->
              <wd-button type="error" size="small" @click="handleBatchDelete" :disabled="!hasSelectedItems"
                class="batch-delete-btn">
                批量删除
              </wd-button>
            </view>

            <!-- 合计栏：仅显示勾选商品的金额 -->
            <view class="cart-summary">
              <view class="summary-info">
                <text class="total-text">合计（仅勾选商品）：</text>
                <text class="total-price">￥{{ cartTotalAmount }}</text>
              </view>
              <wd-button type="primary" class="checkout-btn" :disabled="!hasSelectedItems">
                结算
              </wd-button>
            </view>
          </view>
        </view>
      </scroll-view>
    </wd-action-sheet>
  </view>



</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import Decimal from 'decimal.js'  // 引入decimal.js

import {
  ref,
  nextTick,
  watch,
  computed
} from 'vue'
import HeadNav from '@/components/HeadNav/index.vue'
import {
  useFontSizeStore
} from '@/stores/fontSizeStore';
import {
  jifen_chaoshiApi,
  yaodian_chaoshiApi,
  yiyuan_yuyueApi,
  bangding_shebeiApi,
  yiri_cansanApi,
  shenghuo_leiApi,
} from "@/api/products"

import {
  useRouter
} from 'uni-mini-router'

// 路由实例 - 保留原逻辑
const router = useRouter();



const fontSizeStore = useFontSizeStore();


// 购物车相关状态
const cartCategories = ref([]) // 按分类整理的购物车商品
const selectAll = ref(false) // 全选状态


// 当前激活的Tab
const paramName = ref("")
const pageTitle = ref("")
const priceSortValue = ref(0)

const showBottomModel = ref(false);

// 滚动相关（核心修复：确保变量初始化正确）
const rightScrollRef = ref(null)
const contentPositions = ref([]) // 存储分类标题位置，滚动联动依赖此数据
const activeIndex = ref(0)
const leftScrollInto = ref('')
const targetId = ref('')

// 筛选核心状态
const isFilterPopupOpen = ref(false)


// 商品数据
const categories = ref([])

// 计算筛选后的分类和商品
const filteredCategories = computed(() => {
  return categories.value.map(category => {
    let filteredFoods = [...category.foods].filter(food => {
      return true
    })

    return {
      ...category,
      filteredFoods
    }
  }).filter(category => category.filteredFoods.length > 0)
})

// 购物车相关
const cartCount = ref(0)
const totalAmount = ref('0.00')

const calculateCategoryPositions = async () => {
  await nextTick()
  const list = filteredCategories.value
  if (list.length === 0) return

  // 清空旧数据
  contentPositions.value = new Array(list.length).fill(null)

  // 获取滚动容器位置（#rightScrollView）
  const scrollQuery = uni.createSelectorQuery()
  scrollQuery.select('#rightScrollView').boundingClientRect()
  scrollQuery.exec(async (res) => {
    const scrollViewRect = res[0]
    if (!scrollViewRect) return

    // 遍历每个分类，获取其标题位置
    for (let index = 0; index < list.length; index++) {
      const query = uni.createSelectorQuery()
      query.select(`#category-title-${index}`).boundingClientRect()
      query.exec((rectRes) => {
        const rect = rectRes[0]
        if (rect) {
          contentPositions.value[index] = {
            top: rect.top - scrollViewRect.top,
            bottom: rect.bottom - scrollViewRect.top,
            height: rect.height
          }
        } else {
          // 如果获取失败，延迟重试
          setTimeout(() => {
            const retryQuery = uni.createSelectorQuery()
            retryQuery.select(`#category-title-${index}`)
              .boundingClientRect()
            retryQuery.exec(retryRes => {
              const r = retryRes[0]
              if (r) {
                contentPositions.value[index] = {
                  top: r.top - scrollViewRect.top,
                  bottom: r.bottom - scrollViewRect
                    .top,
                  height: r.height
                }
              }
            })
          }, 50)
        }
      })
    }
  })
}

const handleRightScroll = (e) => {
  const scrollTop = e.detail.scrollTop

  if (contentPositions.value.length === 0) return

  // 滚动到顶部时，激活第一个
  if (scrollTop <= 10) {
    if (activeIndex.value !== 0) {
      activeIndex.value = 0
      leftScrollInto.value = 'left-item-0'
    }
    return
  }

  let matchedIndex = -1
  const len = contentPositions.value.length

  // 从后往前找，找到第一个“顶部在视口内”的分类
  for (let i = len - 1; i >= 0; i--) {
    const pos = contentPositions.value[i]
    if (!pos) continue

    const isLast = i === len - 1
    // 匹配规则：当前滚动距离 >= 分类顶部 - 30px，且 < 分类底部 - 30px（或最后一个分类）
    if (scrollTop >= pos.top - 30 && (isLast || scrollTop < pos.bottom - 30)) {
      matchedIndex = i
      break
    }
  }

  // 更新左侧菜单激活状态
  if (matchedIndex !== -1 && activeIndex.value !== matchedIndex) {
    activeIndex.value = matchedIndex
    leftScrollInto.value = `left-item-${matchedIndex}`
  }
}

// 5. 修复分类点击逻辑（确保右侧滚动到对应分类）
let clickTimer = null

const handleCategoryMenuClick = async (index) => {
  // ✅ 防抖：防止频繁点击
  if (clickTimer) clearTimeout(clickTimer)
  clickTimer = setTimeout(() => {
    clickTimer = null
  }, 300)

  if (index < 0 || index >= filteredCategories.value.length) return

  activeIndex.value = index
  leftScrollInto.value = `left-item-${index}`

  await nextTick()
  targetId.value = ''
  await nextTick()
  targetId.value = `category-title-${index}`

  // 延迟触发高亮
  setTimeout(() => {
    const query = uni.createSelectorQuery()
    query.select('#rightScrollView').boundingClientRect()
    query.exec((res) => {
      const rect = res[0]
      if (rect) {
        handleRightScroll({
          detail: {
            scrollTop: rect.scrollTop
          }
        })
      }
    })
  }, 150)
}



// 7. 页面挂载时初始化位置（确保首次加载有数据）
onLoad(async (options) => {
  console.log("out options:", options)
  const name = options.name;
  paramName.value = name;
  await nextTick()
  activeIndex.value = 0
  leftScrollInto.value = 'left-item-0'
  targetId.value = ''

  await nextTick()
  targetId.value = 'category-title-0'


  let res = {};
  /*
    jifen_chaoshiApi,
  yaodian_chaoshiApi,
  yiyuan_yuyueApi,
  bangding_shebeiApi,
  yiri_cansanApi,
  shenghuo_leiApi,
  */

  if (name == 'jifen_chaoshi') {
    res = await jifen_chaoshiApi();
    pageTitle.value = "积分超市"
  } else if (name == 'yaodian_chaoshi') {
    res = await yaodian_chaoshiApi();
    pageTitle.value = "药店超市"
  } else if (name == 'yiyuan_yuyue') {
    res = await yiyuan_yuyueApi();
    pageTitle.value = "医院预约"
  } else if (name == 'bangding_shebei') {
    res = await bangding_shebeiApi();
    pageTitle.value = "绑定设备"
  } else if (name == 'yiri_cansan') {
    res = await yiri_cansanApi();
    pageTitle.value = "一日三餐"
  } else if (name == 'shenghuo_lei') {
    res = await shenghuo_leiApi();
    pageTitle.value = "生活类"
  }

  if (res?.code == 200) {
    res.data.forEach((i) => {
      i.foods.forEach((k) => {
        k.count = 0;
      })
    })
    categories.value = res.data;

    // 延迟计算位置
    setTimeout(() => calculateCategoryPositions(), 200)
  }

})



// 处理商品数量变更（使用decimal.js计算金额）
// const handleGoodsCountChange = (food, delta) => {
//   // 防止数量为负
//   if (food.count + delta < 0) return;

//   // 更新单个商品数量
//   food.count += delta

//   // 初始化计算变量（使用Decimal确保精度）
//   let count = 0
//   const total = new Decimal(0)  // 总金额从0开始计算

//   // 遍历所有商品计算总数量和总金额
//   categories.value.forEach(cat => {
//     cat.foods.forEach(f => {

//       count += f.count  // 数量是整数，直接累加没问题
//       // 金额计算：单价 * 数量，使用decimal.js避免精度问题
// 		 total.plus(new Decimal(f.price).times(f.count))

//     })
//   })

//   // 更新购物车总数
//   cartCount.value = count

//   // 更新总金额（保留两位小数，转为字符串避免精度问题）
//   totalAmount.value = total.toFixed(2)
// }

const handleGoodsCountChange = (food, delta) => {
  if (food.count + delta < 0) return;

  food.count += delta;

  let count = 0;
  let total = new Decimal(0); // 初始化为 0

  categories.value.forEach(cat => {
    cat.foods.forEach(f => {
      count += f.count;
      // ✅ 修复：必须将 plus 的结果重新赋值给 total
      total = total.plus(new Decimal(f.price || 0).times(f.count));
    });
  });

  cartCount.value = count;
  totalAmount.value = total.toFixed(2); // 转为字符串，保留两位小数
};



const handleShowPaymentPopup = () => {
  showBottomModel.value = true
}

const handleHidePaymentPopup = () => {
  showBottomModel.value = false
}

const priceSorthandleChange = ({ value }) => {
  console.log(value)
}

// 监听购物车变化，自动整理分类
watch(
  () => categories.value,
  (newVal) => {
    const cartData = [];
    newVal.forEach(category => {
      // 过滤有数量的商品
      const validGoods = category.foods.filter(item => item.count > 0).map(item => {
        // 查找当前购物车中相同id的商品，保留其勾选状态
        const existingItem = cartCategories.value
          .flatMap(c => c.goods)
          .find(g => g.id === item.id);

        return {
          ...item,
          // 若存在原有商品，复用其checked状态；否则默认false
          checked: existingItem ? existingItem.checked : false
        };
      });

      if (validGoods.length > 0) {
        // 查找当前购物车中相同分类，保留其勾选状态
        const existingCategory = cartCategories.value.find(c => c.name === category.name);
        cartData.push({
          id: category.id || category.name,
          name: category.name,
          // 若存在原有分类，复用其checked状态；否则默认false
          checked: existingCategory ? existingCategory.checked : false,
          goods: validGoods
        });
      }
    });

    cartCategories.value = cartData;
  },
  { deep: true }
);


// 1. 核心：仅计算勾选商品的金额（使用decimal.js确保精度）
// const updateSelectedTotal = () => {
//   let selectedTotal = new Decimal(0)
//   let selectedItemCount = 0

//   // 遍历所有分类，仅累加“分类勾选且商品勾选”的金额
//   cartCategories.value.forEach(category => {
//     if (category.checked) {
//       category.goods.forEach(item => {
//         if (item.checked && item.price != null && typeof item.price === 'number') {
//           // 金额 = 单价 * 数量，decimal.js避免精度问题
//           selectedTotal = selectedTotal.plus(new Decimal(item.price).times(item.count))
//           selectedItemCount += item.count
//         }
//       })
//     }
//   })

//   // 更新购物车总数和合计金额（保留2位小数）
//   cartCount.value = selectedItemCount
//   totalAmount.value = selectedTotal.toFixed(2)
// }
const updateSelectedTotal = () => {
  let selectedTotal = new Decimal(0)
  let selectedItemCount = 0

  cartCategories.value.forEach(category => {
    category.goods.forEach(item => {
      if (item.checked && item.count > 0 && typeof item.price === 'number') {
        selectedTotal = selectedTotal.plus(new Decimal(item.price).times(item.count))
        selectedItemCount += item.count
      }
    })
  })

  cartCount.value = selectedItemCount
  totalAmount.value = selectedTotal.toFixed(2)
}
// 2. 全选功能：同步所有分类和商品的勾选状态
const handleSelectAll = () => {
  cartCategories.value.forEach(category => {
    category.checked = selectAll.value
    category.goods.forEach(item => {
      item.checked = selectAll.value
    })
  })

  // 全选后更新合计
  updateSelectedTotal()
}

// 3. 分类勾选：同步该分类下所有商品的勾选状态
const handleCategoryCheck = (catIndex) => {
  const category = cartCategories.value[catIndex]
  category.goods.forEach(item => {
    item.checked = category.checked
  })
  // 更新全选状态和合计
  updateSelectAllStatus()
  updateSelectedTotal()
}

// 4. 商品勾选：同步分类勾选状态
const handleItemCheck = (catIndex, itemIndex) => {
  const category = cartCategories.value[catIndex]
  // 检查当前分类下所有商品是否都勾选
  const isAllItemChecked = category.goods.every(item => item.checked)
  category.checked = isAllItemChecked
  // 更新全选状态和合计
  updateSelectAllStatus()
  updateSelectedTotal()
}

// 5. 更新全选框状态：所有分类都勾选时，全选框才勾选
const updateSelectAllStatus = () => {
  if (cartCategories.value.length === 0) {
    selectAll.value = false
    return
  }
  selectAll.value = cartCategories.value.every(category => category.checked)
}

// 6. 数量变更：同步更新合计金额
// 修复后的勾选状态被取消问题的数量变更函数
const handleCartCountChange = (item, delta) => {
  // 1. 防止数量小于1（保持原有逻辑）
  if (item.count + delta < 1) return;

  // 2. 保存当前勾选状态（关键：防止后续操作覆盖勾选状态）
  const currentCheckedState = item.checked;

  // 3. 更新购物车商品数量
  item.count += delta;

  // 4. 同步更新原始categories数据（核心修复点）
  categories.value.forEach(cat => {
    const targetItem = cat.foods.find(f => f.id === item.id);
    if (targetItem) {
      // 仅更新数量，不修改原始数据的勾选状态（原始数据可能没有checked字段）
      targetItem.count = item.count;
    }
  });

  // 5. 恢复勾选状态（防止因引用同步导致的状态丢失）
  item.checked = currentCheckedState;

  // 6. 若商品已勾选，更新合计金额
  if (currentCheckedState) {
    updateSelectedTotal();
  }
};

// 7. 分类删除：仅删除当前分类勾选商品，商品≤1时删分类
const handleDeleteCategory = (catIndex) => {
  const targetCat = cartCategories.value[catIndex]
  if (!targetCat) return
  const checkedGoodsIds = targetCat.goods.filter(item => item.checked).map(item => item.id)
  if (checkedGoodsIds.length === 0) return

  // 清除原始数据中勾选商品的数量
  categories.value.forEach(originCat => {
    if (originCat.name === targetCat.name) {
      originCat.foods.forEach(item => {
        if (checkedGoodsIds.includes(item.id)) item.count = 0
      })
    }
  })

  // 剩余商品≤1时删除整个分类
  const remainingGoods = targetCat.goods.length - checkedGoodsIds.length
  if (remainingGoods <= 1) {
    cartCategories.value.splice(catIndex, 1)
  }

  // 更新合计和全选状态
  updateSelectedTotal()
  updateSelectAllStatus()
}

// 8. 批量删除：删除所有分类的勾选商品
const handleBatchDelete = () => {
  cartCategories.value.forEach(category => {
    const checkedGoodsIds = category.goods.filter(item => item.checked).map(item => item.id)
    // 清除原始数据中勾选商品的数量
    categories.value.forEach(originCat => {
      if (originCat.name === category.name) {
        originCat.foods.forEach(item => {
          if (checkedGoodsIds.includes(item.id)) item.count = 0
        })
      }
    })
  })

  // 更新合计和全选状态
  updateSelectedTotal()
  updateSelectAllStatus()
}

// 9. 计算属性：购物车商品总数 + 仅勾选商品的合计金额
const cartGoods = computed(() => {
  return cartCategories.value.flatMap(category => category.goods)
})

const cartTotalAmount = computed(() => {
  // 直接复用计算好的totalAmount，避免重复运算
  return totalAmount.value || '0.00'
})

const hasSelectedItems = computed(() => {
  // 判断是否有勾选商品（用于禁用按钮）
  const val = cartCategories.value.some(category =>
    category.goods.some(item => item.checked)
  )
  return val;
})

// 10. 监听购物车弹窗显示，默认全选
watch(
  () => showBottomModel.value,
  (isShow) => {
    if (isShow) {
      nextTick(() => {
        selectAll.value = true
        handleSelectAll()
      })
    }
  }
)

const actionCart = () => {
  handleSelectAll();
  const list = JSON.stringify(cartCategories.value)
  uni.setStorage({
    key: 'common_yuyue_key',
    data: list,
    success: function () {
      router.push({
        name: "common_yuyue"
      })
    }
  });

  // uni.setStorageSync("common_yuyue",)
}

</script>

<style lang="less" scoped>
@import url("@/static/styles/family/onlineSupermarket/index.less");


.cat_name {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>